package com.example.nettyclient.client;

import com.example.nettyclient.init.SimpleChatClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author PC
 */
public class NettyChatClient {

    private final static Logger logger = LoggerFactory.getLogger(NettyChatClient.class);

    private final static String QUIT_COMMAND = "quit";

    public static void main(String[] args) {
        new NettyChatClient().run();
    }

    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new SimpleChatClientInitializer());
            Channel channel = bootstrap.connect("127.0.0.1", 18080).sync().channel();
            try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
                String message;
                while (true) {
                    message = bufferedReader.readLine();
                    if (StringUtils.equals(message, QUIT_COMMAND)){
                        break;
                    }
                    channel.writeAndFlush(message + "\r\n");
                }
            }
            logger.info("断开连接");
            channel.close().sync();
        } catch (Exception e) {
            logger.error("客户端连接发生异常:" + e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
